// 文件或者url都能用来渲染

<template>
  <div class="c_cdd-pdf-vue">
    <template v-for="(src, index) of c_imgs" v-if="c_imgs.length > 0">
      <img class="pdf-img" :src="src" alt="" />
      <div v-if="imgs.length > 1 && index != imgs.length - 1" class="divider" />
    </template>
  </div>
</template>
<script>
import pdfjs from "pdfjs-dist";
import orderBy from "lodash/orderBy";
// 添加worker
pdfjs.GlobalWorkerOptions.workerSrc =
  "https://cdn.bootcdn.net/ajax/libs/pdf.js/2.4.456/pdf.worker.min.js";

/**pdf预览组件 */
export default {
  name: "cddPdfVue",
  data() {
    return {
      imgs: []
    };
  },
  computed: {
    /**最后渲染的图片 */
    c_imgs() {
      if (this.imgs && this.imgs.length > 0) {
        return orderBy(this.imgs, ["pageNumber"]).map(({ value }) => value);
      }
      return [];
    }
  },
  methods: {
    // 获取数据，1是url，2是文件
    getData() {
      let url = this.url;
      return new Promise((reso, reg) => {
        const reader = new FileReader();
        reader.onload = function(e) {
          return reso(e.target.result);
        };
        if (this.file) {
          reader.readAsDataURL(this.file);
        } else if (url && url.startsWith("http")) {
          fetch(url)
            .then(res => {
              return res.blob();
            })
            .then(blob => {
              reader.readAsDataURL(blob.slice(0, blob.size, "application/pdf"));
            });
        } else {
          return reso(url);
        }
      });
    },
    // 渲染图片
    async reanderPdf(file) {
      try {
        const loadingTask = pdfjs.getDocument(file);
        let arr = [];
        if (loadingTask.promise) {
          loadingTask.promise.then(pdf => {
            for (let i = 1; i <= pdf.numPages; i++) {
              pdf.getPage(i).then(async page => {
                arr.push(await this.renderPage(page));
              });
            }
          });
        }
        return arr;
      } catch (err) {
        console.error(`渲染出错`, err);
      }
      // });
    },
    // 渲染pdfpag
    renderPage(page) {
      try {
        return new Promise((reso, rej) => {
          let scale = 2;
          let viewport = page.getViewport({ scale: scale });

          let canvas = document.createElement("canvas");
          let context = canvas.getContext("2d");
          canvas.height = viewport.height;
          canvas.width = viewport.width;

          let renderContext = {
            canvasContext: context,
            viewport: viewport
          };
          page.render(renderContext).promise.then(res => {
            reso({
              pageNumber: page.pageNumber,
              value: canvas.toDataURL("image/png", 1)
            });
          });
        });
      } catch (error) {
        console.error(`randerpage`, error);
      }
    },
    async initPage() {
      try {
        const data = await this.getData();
        this.imgs = await this.reanderPdf(data);
      } catch (error) {
        console.log(`error`, error);
      }
    }
  },
  props: {
    url: {
      type: String,
      default: ""
    },
    file: {
      type: File,
      default() {
        return null;
      }
    }
  },
  watch: {
    file(value) {
      this.initPage();
    }
  },
  mounted() {
    this.initPage();
  }
};
</script>
<style lang="scss">
$bg: #d8d8d8;
.c_cdd-pdf-vue {
  background: $bg;
  width: 100%;
  height: auto;
  .pdf-img {
    width: 100%;
  }
  .divider {
    width: 100%;
    height: 5px;
    background: $bg;
  }
}
</style>
